<?php

namespace App\Kuafu\Invoice\Controller\Ext;

use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Invoice\Enum\InvoiceCodeEnum;
use App\Kuafu\Invoice\Service\InvoiceService;
use App\Kuafu\Invoice\Service\MoredoBaseService;
use App\Kuafu\Invoice\Validate\MoredoValidate;
use App\Kuafu\Order\Model\OrderInvoiceModel;
use App\Kuafu\Order\Service\OrderInvoiceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class InvoiceController extends BaseController
{
    /**
     * 开票回调
     * @param Request $request
     * @throws \App\Kuafu\Invoice\Exceptions\InvoiceException
     */
    public function uploadNotify(Request $request)
    {
        Log::channel('invoice')->info("盟度开票回调信息:" . json_encode($request->all(), JSON_UNESCAPED_UNICODE));
        $data    = $request->all();
        $dataArr = InvoiceService::uploadCallbackDataHandle($data['data'][0]['fpData']);
        Log::channel('invoice')->info("盟度开票回调信息-解析:" . json_encode($dataArr, JSON_UNESCAPED_UNICODE));
        $orderId = $dataArr['@attributes']['orderId'];
        if (strpos($orderId, OrderInvoiceModel::ORDER_CALLBACK_RED) !== false) {
            OrderInvoiceService::redCallbackModifyOrder($orderId);
        } else {
            $orderType = OrderInvoiceService::getInvoiceType($orderId);
            OrderInvoiceService::callbackInsertInvoice($orderType['orderId'], $orderType['shopId'], $dataArr);
        }
        return response()->json(['errcode' => 200, 'errmsg' => '接收成功']);
    }

    /**
     * 取消开票回调
     * @param Request $request
     */
    public function cancelNotify(Request $request)
    {
        Log::channel('invoice')->info("盟度取消开票回调信息:" . json_encode($request->all(), JSON_UNESCAPED_UNICODE));
        return response()->json(['errcode' => 200, 'errmsg' => '接收成功']);
    }

    /**
     * 初始化对接信息
     * @param $name
     * @param $ipWhiteList
     * @param $fpUploadUrl
     * @param $fpCancelUrl
     * @throws \App\Kuafu\Invoice\Exceptions\InvoiceException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function init(Request $request)
    {
        $valid = MoredoValidate::moredoInit($request);
        if ($valid) {
            return $this->fail(InvoiceCodeEnum::ERR_400000, $valid);
        }
        $name        = $request->name;
        $ipWhiteList = $request->ipWhiteList;
        $fpUploadUrl = $request->fpUploadUrl;
        $fpCancelUrl = $request->fpCancelUrl;
        $address     = $request->address ?? '';
        $tel         = $request->mobile ?? '';
        $contact     = $request->contact ?? '';
        MoredoBaseService::init($name, $ipWhiteList, $fpUploadUrl, $fpCancelUrl, $address, $tel, $contact);
        return $this->success();
    }

    /**
     * 内部链接跳转至盟度
     * @param Request $request
     */
    public function jumpUrl(Request $request, $orderId)
    {
        $url = InvoiceService::jumpUrl($orderId);
        return redirect()->away($url);
    }

}
